package org.jeecg.modules.quartz.job;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.jeecg.common.modules.order.entity.OrderInfo;
import org.jeecg.common.modules.order.service.IOrderInfoService;
import org.jeecg.common.util.enums.OrderStatusEnum;
import org.jeecg.modules.order.service.AdminOrderService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.weixin4j.pay.WeixinPayException;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author guoyh
 * @ClassName OrderCloseJob
 * @Description 24 小时关闭订单
 * @since 2020/9/2 23:50
 **/
@Slf4j
public class OrderCloseJob implements Job {
    @Resource
    private IOrderInfoService orderInfoService;
    @Resource
    private AdminOrderService adminOrderService;


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("结束订单job开始");
        Stopwatch stopwatch = Stopwatch.createStarted();
        try {
            LambdaQueryWrapper<OrderInfo> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(OrderInfo::getStatus, OrderStatusEnum.DOING.getCode());
            queryWrapper.eq(OrderInfo::getActive,false);
            LocalDateTime yesterday = LocalDateTime.now().minusDays(1);
            List<OrderInfo> list = orderInfoService.list(queryWrapper);
            if (CollectionUtils.isNotEmpty(list)){
                list.stream().filter(item -> {
                    LocalDateTime create = DateUtil.toLocalDateTime(item.getCreateTime());
                    return yesterday.isAfter(create);
                }).forEach(item -> {
                    try {
//                        adminOrderService.doRefund(item,"订单超时，24小时内未回复患者");
                    } catch (Exception e) {
                        log.error("退款异常{}",item.getId(),e);
                    }
                });
            }
        } catch (Exception e) {
            log.error("结束订单job异常",e);
        }
        log.info("结束订单job结束，耗时：{}毫秒",stopwatch.elapsed(TimeUnit.MILLISECONDS));

    }
}
